<template>
  <div>
    <div class="table-container">
      <h1 style="font-weight: bold;">记账凭证</h1>
    </div>
    <div style="padding-left: 260px;">
      <el-select v-model="voucher.word" size="large" style="width: 100px">
        <el-option v-for="item in word" :key="item.word" :label="item.word" :value="item.word" />
      </el-select>
      <el-input v-model="voucher.code" style="width: 80px;height: 40px; padding-left: 10px;" />
      <span style="padding-left: 10px;padding-right: 10px;">号</span>
      <span style="padding-right: 10px;">日期</span>
      <el-date-picker v-model="voucher.voucherDate" type="date" :disabled-date="disabledDate"
        style="height: 40px; width: 140px;" />
      <el-button type="primary" class="add-button" style="margin-left: 570px; height: 40px;"
        @click="addVouchers">保存</el-button>
      <el-button type="success" class="add-button" @click="dialogVisible = true"
        style="margin-left: 10px; height: 40px;">新增条目</el-button>
    </div>
    <div class="table-container">
      <el-dialog v-model="dialogVisible" title="新增凭证条目" width="500">
        <el-form :model="form" label-width="auto" style="max-width: 600px">
          <el-form-item label="摘要">
            <el-autocomplete v-model="form.summary" :fetch-suggestions="querySearch" clearable />
          </el-form-item>
          <el-form-item label="会计科目">
            <el-select v-model="form.subjectName" filterable="true" style="width: 240px">
              <el-option v-for="item in subject" :key="item.id" :label="item.code + ' ' + item.name"
                :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="借方金额">
            <el-input v-model="form.debitAmount" @input="validateNumber('debitAmount')" />
          </el-form-item>
          <el-form-item label="贷方金额">
            <el-input v-model="form.creditAmount" @input="validateNumber('creditAmount')" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确认</el-button>
          </div>
        </template>
      </el-dialog>

      <table border="1">
        <tr>
          <th rowspan="2">摘要</th>
          <th rowspan="2">会计科目</th>
          <th colspan="11" class="debit-header">借方金额</th>
          <th colspan="11" class="credit-header">贷方金额</th>
        </tr>
        <tr>
          <td v-for="item in titleArray" :key="item">{{ item }}</td>
          <td v-for="item in titleArray" :key="item">{{ item }}</td>
        </tr>
        <tr class="dataRow" v-for="(item, index) in dataArray" :key="index">
          <td>{{ item.name }}</td>
          <td>{{ item.subject }}</td>
          <td v-for="(cell, cellIndex) in item.debit" :key="cellIndex" class="debit-cell">
            {{ cell }}
          </td>
          <td v-for="(cell, cellIndex) in item.credit" :key="cellIndex" class="credit-cell">
            {{ cell }}
          </td>
        </tr>
        <tr>
          <th colspan="2">合计:{{ sumStr }}</th>
          <td v-for="(cell, cellIndex) in debitSumArray" :key="cellIndex" class="debit-cell">
            {{ cell }}
          </td>
          <td v-for="(cell, cellIndex) in creditSumArray" :key="cellIndex" class="credit-cell">
            {{ cell }}
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { listSubject } from '../../../api/system/subject'
import { addVoucher } from '../../../api/system/voucher'
import { listWord } from '../../../api/system/word'
import { ElMessage } from "element-plus";
interface RestaurantItem {
  value: string
  link: string
}

const restaurants = ref<RestaurantItem[]>([])
const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value
  // call callback function to return suggestions
  cb(results)
}
const createFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}
const word = ref([])
const loadAll = () => {
  return [
    { value: '学费', link: 'https://github.com/vuejs/vue' },
    { value: '收入', link: 'https://github.com/ElemeFE/element' },
    { value: '采购', link: 'https://github.com/ElemeFE/cooking' },
    { value: '差旅费', link: 'https://github.com/ElemeFE/mint-ui' },
    { value: '房租', link: 'https://github.com/vuejs/vuex' },
    { value: '提现', link: 'https://github.com/vuejs/vue-router' },
    { value: '购入固定资产', link: 'https://github.com/babel/babel' },
  ]
}
const validateNumber = (field: string) => {
  form.value[field] = form.value[field].replace(/[^\d]/g, '');
}

const voucher = ref({
  word: '',
  code: 1,
  remark: '',
  voucherDate: new Date(),
  accountSetsId: '',
  submitArray: [],
  subjectId: '',
  subjectCode: ''
})
const subject = ref('')

const getWordList = () => {
  const sestsId = sessionStorage.getItem('setsId');
  if (sestsId == null) {
    ElMessage({
      message: '请先选择账套',
      type: 'warning'
    })
    return false
  }
  listWord(sestsId).then(res => {
    console.log("凭证返回数据为:", res)
    word.value = res.rows
  })
}

const addVouchers = () => {
  console.log("凭证数据为:", voucher.value)

  const accountSetsId = sessionStorage.getItem('setsId')
  voucher.value.accountSetsId = accountSetsId

  addVoucher(voucher.value).then(res => {
    console.log("凭证返回数据为:", res)
    if (res.code == 200) {
      ElMessage.success('保存成功')
    } else {
      ElMessage.error(res.msg)
    }
  })

}


const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}


const dataIndex = ref(0)


const dialogVisible = ref(false)
const titleArray = ref(['亿', '千', '百', '十', '万', '千', '百', '十', '元', '角', '分']);
const dataArray = ref([
  { name: '', subject: '', debit: ['', '', '', '', '', '', '', '', '', '', ''], credit: ['', '', '', '', '', '', '', '', '', '', ''] },
  { name: '', subject: '', debit: ['', '', '', '', '', '', '', '', '', '', ''], credit: ['', '', '', '', '', '', '', '', '', '', ''] },
  { name: '', subject: '', debit: ['', '', '', '', '', '', '', '', '', '', ''], credit: ['', '', '', '', '', '', '', '', '', '', ''] },
  { name: '', subject: '', debit: ['', '', '', '', '', '', '', '', '', '', ''], credit: ['', '', '', '', '', '', '', '', '', '', ''] }
]);

const debitSumArray = ref(['', '', '', '', '', '', '', '', '', '', ''])
const creditSumArray = ref(['', '', '', '', '', '', '', '', '', '', ''])

const form = ref({
  summary: '',
  subjectName: '',
  debitAmount: '',
  creditAmount: ''
})

const numToChinese = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
const units = ['', '拾', '佰', '仟', '万', '拾万', '佰万', '仟万', '亿', '拾亿', '佰亿', '仟亿'];

const sumStr = ref('')

const getSubjectList = () => {
  const sestsId = sessionStorage.getItem('setsId');
  if (sestsId == null) {
    ElMessage.error('请先选择账套')
    return false
  }

  listSubject(sestsId).then(res => {
    subject.value = res.rows
  })
}


function integerToChinese(integer) {
  if (integer === '0') return numToChinese[0];
  let result = '';
  let zeroCount = 0;
  for (let i = 0; i < integer.length; i++) {
    const digit = parseInt(integer[i]);
    const position = integer.length - i - 1;
    const unit = units[position];
    if (digit === 0) {
      zeroCount++;
    } else {
      if (zeroCount > 0) {
        result += numToChinese[0];
      }
      zeroCount = 0;
      result += numToChinese[digit] + unit;
    }
  }
  // 处理结果中的连续单位问题（如“壹拾万”应改为“壹万”）
  result = result.replace(/壹拾/, '壹');
  // 去除末尾的零（如“壹万零”应改为“壹万”）
  result = result.replace(/零+$/, '');
  // 处理“万”和“亿”前面的零（如“零万”应改为“万”，“零亿”应特殊处理为“零”）
  result = result.replace(/(万|亿)零+$/, '$1');
  result = result.replace(/^零+万/, '万');
  result = result.replace(/^零+$/, numToChinese[0]);

  console.log(result)
  return result;
}

function decimalToChinese(decimal) {
  if (!decimal) return '';
  let result = '';
  for (let i = 0; i < decimal.length; i++) {
    const digit = parseInt(decimal[i]);
    const unit = i === 0 ? '角' : '分';
    result += numToChinese[digit] + unit;
  }
  // 去除末尾的“零分”
  result = result.replace(/零分$/, '');
  return result;
}

function numberToRMBChinese(num) {
  const [integerPart, decimalPart] = num.toString().split('.');
  const integerChinese = integerToChinese(integerPart);
  const decimalChinese = decimalToChinese(decimalPart);
  return integerChinese + (decimalChinese ? '整' + decimalChinese : '元整');
}

const submitForm = () => {
  dataArray.value[dataIndex.value].name = form.value.summary
  dataArray.value[dataIndex.value].subject = form.value.subjectName

  if (form.value.debitAmount != undefined && form.value.debitAmount != '') {
    const intDebitValue = Number(form.value.debitAmount) * 100;
    const debitValue = String(intDebitValue).split("")
    // 将 debitValue 数组补位为 11，前面位数用 '' 占位
    while (debitValue.length < 11) {
      debitValue.unshift('');
    }
    dataArray.value[dataIndex.value].debit = debitValue
  }

  if (form.value.creditAmount != undefined && form.value.creditAmount != '') {
    const intCreditValue = Number(form.value.creditAmount) * 100;
    const creditValue = String(intCreditValue).split("")
    while (creditValue.length < 11) {
      creditValue.unshift('');
    }
    dataArray.value[dataIndex.value].credit = creditValue
  }

  voucher.value.submitArray.push(form.value)

  dataIndex.value = dataIndex.value + 1

  dialogVisible.value = false
  form.value = {
    summary: '',
    subjectName: '',
    debitAmount: '',
    creditAmount: ''
  }

  // 计算合计
  let debitSum = 0
  let creditSum = 0

  for (let i = 0; i < voucher.value.submitArray.length; i++) {
    debitSum += Number(voucher.value.submitArray[i].debitAmount);
    creditSum += Number(voucher.value.submitArray[i].creditAmount);
  }

  if (debitSum != 0) {
    const intDebitSum = debitSum * 100;
    const intDebitSumValue = String(intDebitSum).split("")
    // 将 debitValue 数组补位为 11，前面位数用 '' 占位
    while (intDebitSumValue.length < 11) {
      intDebitSumValue.unshift('');
    }
    debitSumArray.value = intDebitSumValue

    // 将 intDebitSum 转为人民币大写
    sumStr.value = numberToRMBChinese(debitSum);
  }

  if (creditSum != 0) {
    const intCreditSum = creditSum * 100;
    const intCreditSumValue = String(intCreditSum).split("")
    while (intCreditSumValue.length < 11) {
      intCreditSumValue.unshift('');
    }
    creditSumArray.value = intCreditSumValue
  }



}
const checkSetsId = () => {
  if (sessionStorage.getItem('setsId') == null) {
    ElMessage.warning('请选择账套！')
    return false
  } else {

    return true
  }
}

onMounted(() => {
  getWordList();
  checkSetsId();
  getSubjectList()
  restaurants.value = loadAll()
})

</script>

<style scoped>
.table-container {
  display: flex;
  flex-direction: column;
  /* 垂直排列子元素 */
  align-items: center;
  /* 水平居中对齐 */
  margin-top: 20px;
  /* 可选：添加一些顶部间距 */
}

.add-button {
  margin-bottom: 10px;
  /* 可选：添加一些按钮和表格之间的间距 */
}

table {
  border-collapse: collapse;
  /* 合并边框 */
  border: 1px solid black;
  /* 单实线边框 */
}

th,
td {
  border: 1px solid black;
  /* 单实线边框 */
  padding: 8px;
  /* 可选：添加一些内边距 */
  text-align: center;
  /* 可选：居中文本 */
}

th {
  width: 200px;
  height: 40px;
}

td {
  height: 80px;
}

.debit-header {
  background-color: green;
}

.debit-cell {
  background-color: lightgreen;
}

.credit-header {
  background-color: red;
}

.credit-cell {
  background-color: orange;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}








/* === 统一字体和基础样式 === */
* {
  font-family: "Arial", sans-serif;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 页面容器 */
.table-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
  padding: 20px;
  width: 100%;
}

/* 标题样式 */
h1 {
  font-size: 24px;
  color: #333;
  font-weight: bold;
  margin-bottom: 20px;
}

/* === 输入框 & 按钮样式 === */
.el-input,
.el-select,
.el-date-picker {
  width: 150px;
  height: 38px;
  font-size: 14px;
  border-radius: 6px;
}

/* 按钮优化 */
.el-button {
  border-radius: 8px;
  font-size: 14px;
  padding: 10px 20px;
  transition: 0.3s;
}

.el-button.primary {
  background-color: #409eff;
  color: white;
  border: none;
}

.el-button.primary:hover {
  background-color: #66b1ff;
}

.el-button.success {
  background-color: #67c23a;
  color: white;
  border: none;
}

.el-button.success:hover {
  background-color: #85ce61;
}

/* === 表格美化 === */
table {
  width: 90%;
  max-width: 1200px;
  margin-top: 20px;
  border-collapse: collapse;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
}

/* 表头 */
th {
  background-color: #f5f5f5;
  color: #333;
  font-weight: bold;
  padding: 12px;
  text-align: center;
}

/* 单元格 */
td {
  padding: 12px;
  text-align: center;
  border: 1px solid #ddd;
}

/* 交替行颜色 */
tr:nth-child(even) {
  background-color: #f9f9f9;
}

/* 鼠标悬停高亮 */
tr:hover {
  background-color: #f1f7ff;
}

/* 借贷方颜色区分 */
.debit-header {
  background-color: #d9f7be;
}

.debit-cell {
  background-color: #e6ffe6;
}

.credit-header {
  background-color: #ffccc7;
}

.credit-cell {
  background-color: #fff2e8;
}

/* === 弹窗优化 === */
.el-dialog {
  border-radius: 10px;
  padding: 20px;
}

/* 弹窗按钮 */
.dialog-footer .el-button {
  border-radius: 5px;
  padding: 8px 16px;
}

/* === 表单布局优化 === */
.el-form-item {
  margin-bottom: 12px;
}

.el-form-item label {
  font-weight: bold;
  color: #555;
}









.button-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, auto));
  justify-content: center;
  gap: 10px;
  margin-top: 10px;
}
</style>
